<template>
  <div class="voting_main" :class="{'pad0':status==3}">
    <head-top head-title="投票" goBack="true"></head-top>
    <img :src="tishi" alt="" v-if="status==3" width="100%" height="100%">
    <p v-if="status==4" style="padding:200px 10px 0px 10px; text-align: center; font-size:16px">投票未开启或投票已下架</p>
    <p v-if="status==2" style="padding:200px 10px 0px 10px; text-align: center; font-size:16px">
      对不起您不是该小区业主，或者去我的房申请进行审核</p>
    <p v-if="status==5" style="padding:200px 10px 0px 10px; text-align: center; font-size:16px">您未绑定手机和真实姓名</p>
    <p v-if="status==6" style="padding:200px 10px 0px 10px; text-align: center; font-size:16px">
      该项投票已领取表决票或已由同套房屋的其他业主完成</p>
    <form action="" v-if="status==1">
      <!--<form action="">-->
      <div class="explain">
        <!--候选人文案-->
        <div class="wrapper" v-if="wenanShow==2">
          <span>注意：</span>
          本次选举候选人共有<span style="color: red">{{candadites.length}}</span>个人，你最多只能投<span
          style="color: red">{{detail.check_limit}}</span>个人。如果在投票截止时间，逾期未参与投票，线上投票将会关闭。
          投票的截止时间为：<br>
          <span>{{detail.start_time * 1000 | dateFmt(('YYYY.MM.DD HH:mm'))}}~{{detail.end_time * 1000 | dateFmt(('YYYY.MM.DD HH:mm'))}}</span>
          <span style="float: right; color: #0078de;" @click="$router.push('/home/VillageDetail/' + detail.article_id+'/'+'vote')">查看详情</span>
          <div style="font-size: 15px;">你已同意<span style="color: red">{{agree}}</span>个，还可以选择<span
            style="color: red">{{detail.check_limit - agree}}</span>个
          </div>
        </div>
        <!--事物文案-->
        <div class="wrapper" v-if="wenanShow==1">
          <span>注意：</span>
          本次投票共有<span style="color: red">{{candadites.length}}</span>事项，最可选<span
          style="color: red">{{detail.check_limit}}</span>事项。如果在投票截止时间，逾期未参与投票，线上投票将会关闭。
          投票的截止时间为：<br>
          <span>{{detail.start_time * 1000 | dateFmt(('YYYY.MM.DD HH:mm'))}}~{{detail.end_time * 1000 | dateFmt(('YYYY.MM.DD HH:mm'))}}</span>
          <span style="float: right; color: #0078de;" @click="$router.push('/home/VillageDetail/' + detail.article_id+'/'+'vote')">查看详情</span>
          <div style="font-size: 15px;">你已同意<span style="color: red">{{agree}}</span>事项，还可以选择<span
            style="color: red">{{detail.check_limit - agree}}</span>事项
          </div>
        </div>
      </div>
      <ul>
        <li class="candidate border-bottom-last" v-for="(item,index) in candadites" :key="index">
          <div class="introduce">
            <div class="img_people">
              <img
                :src="item.img_moblie_url?item.img_moblie_url:defaultImg"
                alt="">
            </div>
            <div class="content_word">
              <div class="word_top">
                <div class="name_div">
                  <p>{{item.name}}</p>
                  <span v-show="item.political!==null && item.political!==''">-- {{item.political}}</span>
                </div>

                <!-- <span>2017.11.1 13:30</span> -->
              </div>
              <div class="word_bottom">
                <p>{{item.house}}</p>
                <span v-if="wenanShow==2" @click="toVotingDetail(item.vote_candidate_id,wenanShow)">查看个人简历</span>
                <span v-if="wenanShow==1" @click="toVotingDetail(item.vote_candidate_id,wenanShow)">查看详细内容</span>
              </div>
            </div>
          </div>
          <div class="answer">
            <label v-show="agreeTrue === 'agree'" :for="`${1}_${detail.vote_id}_${item.vote_candidate_id}`">
              <input @click="submit" class="same" type="radio" :name="item.vote_candidate_id"
                     :value="`${1}_${detail.vote_id}_${villageId}_${userId}`"
                     :id="`${1}_${detail.vote_id}_${item.vote_candidate_id}`"
                     :key="`${1}_${detail.vote_id}_${item.vote_candidate_id}`">
              <span class="xiangtong"></span>同意
            </label>
            <label v-show="opposeTrue === 'oppose'" :for="`${2}_${detail.vote_id}_${item.vote_candidate_id}`">
              <input @click="submit" class="same" type="radio" :name="item.vote_candidate_id"
                     :value="`${2}_${detail.vote_id}_${villageId}_${userId}`"
                     :id="`${2}_${detail.vote_id}_${item.vote_candidate_id}`"
                     :key="`${2}_${detail.vote_id}_${item.vote_candidate_id}`">
              <span class="xiangtong"></span>反对
            </label>
            <!--<label :for="`${3}_${detail.vote_id}_${item.vote_candidate_id}`">
              <input @click="submit" class="same" type="radio" :name="item.vote_candidate_id"
                     :value="`${3}_${detail.vote_id}_${villageId}_${userId}`"
                     :id="`${3}_${detail.vote_id}_${item.vote_candidate_id}`">
              <span class="xiangtong"></span>随多数
            </label>
            <label :for="`${4}_${detail.vote_id}_${item.vote_candidate_id}`">
              <input @click="submit" class="same" type="radio" :name="item.vote_candidate_id"
                     :value="`${4}_${detail.vote_id}_${villageId}_${userId}`"
                     :id="`${4}_${detail.vote_id}_${item.vote_candidate_id}`">
              <span class="xiangtong"></span>弃权
            </label>-->
          </div>
        </li>
      </ul>
    </form>
    <div class="confirmbtn" v-show="status==1">
      <!--<div class="confirmbtn">-->
      <label v-show="waiverTrue ==='waiver'" class="checkbox-label" @click="giveupBtn">
        <input type="radio"
               class="checkbox-input giveup-input"/>
        <span class="checkbox-core"></span>
        <span class="text">弃权</span>
      </label>
      <label v-show="mostTrue==='most'" class="checkbox-label" @click="moreBtn">
        <input type="radio"
               class="checkbox-input more-input"/>
        <span class="checkbox-core"></span>
        <span class="text">随多数</span>
      </label>
      <!--随多数和弃权其中一个-->
      <button v-if="mostTrue || waiverTrue" class="sure_btn" @click="sureSubmitBottom">
        <span>确认</span>
      </button>
      <!--当随多数和弃权都没有显示-->
      <button v-if="!mostTrue && !waiverTrue" style="width: 100%" class="sure_btn" @click="sureSubmitBottom">
        <span>确 认</span>
      </button>
    </div>
    <!--直接同意的弹窗-->
    <mt-popup
      v-model="popupVisible"
      popup-transition="popup-fade" :closeOnClickModal="false" class="popup-wrapper">
      <div class="popup">
        <p class="tishi">提示</p>
        <p class="desc">你已同意<span style="color: red">{{agree}}</span>个，请确认投票或重新投票</p>
        <div class="sure-reset">
          <span class="reset clearfix" @click="reset">重新投票</span>
          <span class="sure clearfix" @click="sureSubmit">确认投票</span>
        </div>
      </div>
    </mt-popup>
    <!--点击最下面确认按钮的弹窗-->
    <mt-popup
      v-model="sureVisible"
      popup-transition="popup-fade" :closeOnClickModal="false" class="popup-wrapper">
      <div class="popup">
        <p class="tishi">提示</p>
        <p class="desc-bottom" v-show="data.length">你已同意<span style="color: red">{{agree}}</span>个，还可同意<span
          style="color: red">{{detail.check_limit - agree}}</span>个，你可以继续投票或者直接确认投票</p>
        <p class="desc-bottom" v-show="data.length===0">你还未投票</p>
        <div class="sure-reset">
          <span class="reset" @click="resetBottom" v-show="data.length">继续投票</span>
          <span class="reset" @click="resetBottom" v-show="data.length===0"
                style=" width: 100%;color: #0078de;padding-top:10px;border-right:none;text-align: center;">去投票</span>
          <span class="sure" @click="sureSubmit" v-show="data.length">确认投票</span>
        </div>
      </div>
    </mt-popup>
    <!--随多数按钮弹窗-->
    <mt-popup
      v-model="moreVisible"
      popup-transition="popup-fade" :closeOnClickModal="false" class="popup-wrapper">
      <div class="popup">
        <p class="tishi">提示</p>
        <p class="desc">你已<span style="color: red">全部选择随多数</span>，请确认投票或重新投票</p>
        <div class="sure-reset">
          <span class="reset clearfix" @click="reset">重新投票</span>
          <span class="sure clearfix" @click="moreSubmit">确认投票</span>
        </div>
      </div>
    </mt-popup>
    <!--弃权按钮弹窗-->
    <mt-popup
      v-model="giveupVisible"
      popup-transition="popup-fade" :closeOnClickModal="false" class="popup-wrapper">
      <div class="popup">
        <p class="tishi">提示</p>
        <p class="desc">你已<span style="color: red">全部选择弃权</span>，请确认投票或重新投票</p>
        <div class="sure-reset">
          <span class="reset clearfix" @click="reset">重新投票</span>
          <span class="sure clearfix" @click="giveupSubmit">确认投票</span>
        </div>
      </div>
    </mt-popup>
  </div>
</template>
<style lang="scss" scoped>
  @import "../../common/sass/mixin.scss";

  .mint-indicator-wrapper {
    z-index: 2003;
  }

  .mint-indicator-mask {
    top: 0;
    left: 0;
    position: fixed;
    width: 100%;
    height: 100%;
    opacity: 0.4;
    background: #000;
    z-index: 2003;
  }

  .voting_main {
    width: 100%;
    height: 100%;
    padding-top: 40px;
    padding-bottom: 10%;
    background: white;
    .explain {
      position: fixed;
      top: 0;
      left: 0;
      height: 120px;
      background-color: #f2f2f2;
      padding-top: 40px;
      z-index: 1;
      .wrapper {
        font-size: 13px;
        line-height: 20px;
        padding: 10px;
        span:first-child {
          color: #ff2a2a;
        }
        span:last-child {
          color: #0078de;
        }
      }
    }
    ul {
      padding-top: 110px;
      -webkit-overflow-scrolling: touch;
      .candidate {
        width: 100%;
        height: 112px;
        .introduce {
          width: 100%;
          height: 70px;
          margin-top: 10px;
          .img_people {
            padding-top: 10px;
            padding-left: 10px;
            float: left;
            width: 14%;
            img {
              width: 44px;
              height: 44px;
              border-radius: 50%;
            }
          }
          .content_word {
            float: left;
            width: 80%;
            .word_top {
              margin-top: 10px;
              height: 22px;
              .name_div{
                float: left;
                width: 100%;
                /*width: 170px;*/
                overflow: hidden;
                text-overflow: ellipsis;
                white-space: nowrap;
                display: flex;
                align-items: center;
                p {
                  font-size: 15px;
                }
                span{
                  font-size: 14px;
                  color: #595959;
                  margin-left: 10px;
                }
              }

              span {
                float: right;
                font-size: 10px;
                color: #999999;
                /*margin-right: 5px;*/
              }
            }
            .word_bottom {
              height: 22px;
              line-height: 22px;
              p {
                font-size: 12px;
                float: left;
                color: #666666;
                width: 180px;
                overflow: hidden;
                text-overflow: ellipsis;
                white-space: nowrap;
              }
              span {
                float: right;
                font-size: 12px;
                color: #0078de;
                /*margin-right: 5px;*/
              }
            }
          }
        }
        .answer {
          width: 100%;
          text-align: right;
          font-size: 16px;
          label {
            /*float: right;*/
            width: 25%;
            padding-right: 12px;
          }
        }
        .same {
          display: none;
        }
        .xiangtong {
          position: relative;
          background-color: #fff;
          border: 1px solid rgba(0, 0, 0, 0.15);
          border-radius: 100%;
          display: inline-block;
          width: 16px;
          height: 16px;
          margin-right: 4px;
          vertical-align: middle;
          z-index: 0;
        }
        .same:checked + .xiangtong:after {
          background-color: #0078de;
          border-radius: 100%;
          content: "";
          position: absolute;
          // display: inline-block;
          height: 10px;
          width: 10px;
          top: 3px;
          right: 3px;
        }
      }
    }
    .confirmbtn {
      width: 100%;
      height: 44px;
      background: #f5f5f5;
      text-align: center;
      position: fixed;
      z-index: 2;
      bottom: 0;
      border-top: 1px solid #d9d9d9;
      display: inline-flex;
      justify-content: space-between;
      .checkbox-label {
        padding: 0 0.1rem;
        display: flex;
        align-items: center;
        width: 25%;
        background: #f5f5f5;
        padding-left: 10px;
      }
      .checkbox-label .text {
        padding-left: 5px;
        font-size: 14px;
      }
      .checkbox-label .checkbox-input {
        display: none;
        opacity: 0;
      }

      .checkbox-label .checkbox-core {
        display: inline-block;
        border-radius: 100%;
        border: 1px solid #c2c2c2;
        position: relative;
        width: 20px;
        height: 20px;
        vertical-align: middle;
      }

      .checkbox-core:after {
        border: 2px solid transparent;
        border-left: 0;
        border-top: 0;
        content: " ";
        top: 1px;
        left: 7px;
        position: absolute;
        width: 6px;
        height: 12px;
        -webkit-transform: rotate(45deg) scale(0);
        transform: rotate(45deg) scale(0);
        -webkit-transition: -webkit-transform .2s;
        transition: -webkit-transform .2s;
        transition: transform .2s;
        transition: transform .2s, -webkit-transform .2s;
      }

      .checkbox-input:checked + .checkbox-core {
        background-color: #26a2ff;
        border-color: #26a2ff;
      }

      .checkbox-input:checked + .checkbox-core:after {
        border-color: #fff;
        -webkit-transform: rotate(45deg) scale(1);
        transform: rotate(45deg) scale(1);
      }
      .sure_btn {
        width: 165px;
        height: 44px;
        background: #0078de;
        outline: none;
        border-radius: 0;
        span {
          font-size: 15px;
          text-align: center;
          color: #fff;
        }
      }
    }
    .popup-wrapper {
      width: 70%;
      height: 28%;
      border-radius: 15px;
      .popup {
        padding: 10px 0;
        p {
          text-align: center;
        }
        .tishi {
          margin-bottom: 20px;
          font-size: 18px;
          font-weight: 700;
        }
        .desc-bottom {
          font-size: 15px;
          color: #666;
          padding: 0 10px 23px 10px;
          line-height: 16px;
        }
        .desc {
          font-size: 15px;
          color: #666;
        }
        .sure-reset {
          width: 100%;
          font-size: 16px;
          position: absolute;
          bottom: 0;
          left: 0;
          border-top: 1px solid #f0f0f0;
          .reset {
            padding: 10px 0;
            display: inline-block;
            text-align: center;
            width: 50%;
            color: #666;
            border-right: 1px solid #f0f0f0;
          }
          .sure {
            text-align: center;
            width: 49%;
            padding: 10px 0;
            float: right;
            color: #0078de;
          }
        }
      }
    }
  }

  .pad0 {
    padding-top: 40px;
    padding-bottom: 0;
  }
</style>
<script>
  import headTop from '../header/Header.vue'
  import {
    loadVillageId,
    // loadOpenId,
    loadUserId
  } from '../../common/js/cache.js'
  import commonUrl from '../../common/js/commonUrl.js'
  import qs from 'qs'
  import $ from 'jquery'
  import { Toast, Indicator } from 'mint-ui'
  import { getVotingList } from '../../api/satisfaction'

  export default {
    name: 'Voting',
    data () {
      return {
        defaultImg: require('./images/man_icon@2x.png'),
        wenanShow: {
          type: Number
        },
        detail: {},
        // length: {
        //   type: Number
        // },
        userId: loadUserId(),
        data: [],
        popupVisible: false,
        sureVisible: false,
        moreVisible: false,
        giveupVisible: false,
        tishi: '',
        status: {
          type: Number
        },
        villageId: loadVillageId(),
        loaded: false,
        agree: 0,
        agreeTrue: '', // 投票选项显示 同意
        mostTrue: '', // 投票选项显示 随多数
        opposeTrue: '', // 投票选项显示  反对
        waiverTrue: '' // 投票选项显示 弃权
      }
    },
    created () {
      this._getVotingList()
      this.candadites = []
      // this.getVotingList()
      this.wenanShow = this.$route.params.type
      console.log(this.wenanShow)
    },
    components: {
      headTop
    },
    beforeRouteEnter: (to, from, next) => {
      if (from.name === 'VotingDetail') {
        to.meta.isBack = true
      }
      next()
    },
    activated () {
      if (!this.$route.meta.isBack) {
        this._getVotingList()
      }
      this.$route.meta.isBack = false
    },
    methods: {
      toVotingDetail (id, type) {
        this.$router.push('/home/VotingDetail/' + id + '/' + type + '/' + 'old')
      },
      _getVotingList () {
        getVotingList(this.$route.params.id).then(res => {
          // console.log(res)
          if (res.code === 200) {
            this.status = res.data.status
            if (this.status === 1) {
              this.detail = res.data
              this.candadites = res.data.candadites
              // console.log(this.candadites)
              // 投票选项显示
              this.agreeTrue = res.data.voteType.agree // 同意
              this.mostTrue = res.data.voteType.most // 随多数
              this.opposeTrue = res.data.voteType.oppose // 反对
              this.waiverTrue = res.data.voteType.waiver // 弃权
            }
          }
        })
      },
      submit () {
        $('.giveup-input').prop('checked', false)
        $('.more-input').prop('checked', false)
        // 获取form表单中的值
        var dataStr = $('form').serialize()
        // 字符串拼接成后台想要的数据
        var dataArr = dataStr.split('=').join('_').split('&')
        var data = []
        // 定义变量存放数据变化
        var j = 0
        dataArr.forEach((item, index) => {
          // 如果选择的数为1(同意)的就让j累加
          if (item.split('_')[1] === '1') {
            j++
          }
          data.push(item.split('_'))
        })
        this.agree = j
        this.data = data
        if (j >= this.detail.check_limit) {
          this.popupVisible = true
          // return
        }
      },
      sureSubmit () {
        this.popupVisible = false
        this.sureVisible = false
        Indicator.open({
          text: '投票中...',
          spinnerType: 'fading-circle'
        })
        const url = `${commonUrl.apihost}index.php/home/Vote_Result/setCandidate`
        const datas = {
          type: 'other',
          data: this.data
        }
        this.$http.post(url, qs.stringify(datas), {headers: {'Content-Type': 'application/x-www-form-urlencoded'}}).then(res => {
          // console.log(res)
          if (res.data.code === 200) {
            Indicator.close()
            Toast({
              message: res.data.data.message,
              position: 'middle',
              duration: 1000
            })
            this.popupVisible = false
            this.sureVisible = false
            // flag 1:表示页面跳转  0:表示不跳转
            if (res.data.data.flag === 1) {
              if (res.data.data.data.type === 'vote') {
                this.$router.replace('/home/Vote/' + res.data.data.data.id)
              } else if (res.data.data.data.type === 'voting') {
                this.$router.replace('/home/voting/' + res.data.data.data.id + '/' + res.data.data.data.can_type)
                this.$router.go(0) // 刷新
                this._getVotingList()
              } else if (res.data.data.data.type === 'TakeIn') {
                this.$router.replace('/home/TakeIn/' + res.data.data.data.id)
              } else if (res.data.data.data.type === 'TakeScore') {
                this.$router.replace('/home/SatisForm/' + res.data.data.data.id)
              }
            } else if (res.data.data.flag === 0) {
              // this.$router.go(-6)
              this.$router.replace('/home')
            }
          }
          if (res.data.code === 400) {
            Indicator.close()
            this.sureVisible = false
            Toast({
              message: res.data.error,
              position: 'middle',
              duration: 2000
            })
            // this.$router.go(0)
          }
        })
      },
      sureSubmitBottom () {
        this.sureVisible = true
      },
      reset () {
        this.popupVisible = false
        this.moreVisible = false
        this.giveupVisible = false
        $('.same').prop('checked', false)
        $('.more-input').prop('checked', false)
        $('.giveup-input').prop('checked', false)
        this.data = []
        this.$router.go(0) // 刷新
      },
      resetBottom () {
        this.sureVisible = false
      },
      // 随多数按钮
      moreBtn () {
        $('.giveup-input').prop('checked', false)
        $('.same').prop('checked', false)
        this.moreVisible = true
      },
      // 随多数确认投票
      moreSubmit () {
        Indicator.open({
          text: '投票中...',
          spinnerType: 'fading-circle'
        })
        const url = `${commonUrl.apihost}index.php/home/Vote_Result/setCandidate`
        const datas = {
          type: 'most',
          vote_id: this.detail.vote_id,
          area_id: loadVillageId(),
          user_id: loadUserId()
        }
        this.$http.post(url, qs.stringify(datas), {headers: {'Content-Type': 'application/x-www-form-urlencoded'}}).then(res => {
          // console.log(res)
          if (res.data.code === 200) {
            Indicator.close()
            Toast({
              message: res.data.data.message,
              position: 'middle',
              duration: 1000
            })
            // this.popupVisible = false
            // this.sureVisible = false
            this.moreVisible = false
            // flag 1:表示页面跳转  0:表示不跳转
            if (res.data.data.flag === 1) {
              if (res.data.data.data.type === 'vote') {
                this.$router.replace('/home/Vote/' + res.data.data.data.id)
              } else if (res.data.data.data.type === 'voting') {
                this.$router.replace('/home/voting/' + res.data.data.data.id + '/' + res.data.data.data.can_type)
                this.$router.go(0) // 刷新
                this._getVotingList()
              } else if (res.data.data.data.type === 'TakeIn') {
                this.$router.replace('/home/TakeIn/' + res.data.data.data.id)
              } else if (res.data.data.data.type === 'TakeScore') {
                this.$router.replace('/home/SatisForm/' + res.data.data.data.id)
              }
            } else if (res.data.data.flag === 0) {
              // this.$router.go(-6)
              this.$router.replace('/home')
            }
          }
          if (res.data.code === 400) {
            Indicator.close()
            Toast({
              message: '对不起，该项投票已由同套房屋的其他业主完成',
              position: 'middle',
              duration: 2000
            })
            this.$router.go(0)
          }
        })
      },
      // 全部弃权按钮
      giveupBtn () {
        $('.same').prop('checked', false)
        $('.more-input').prop('checked', false)
        this.giveupVisible = true
      },
      // 弃权确认投票
      giveupSubmit () {
        Indicator.open({
          text: '投票中...',
          spinnerType: 'fading-circle'
        })
        const url = `${commonUrl.apihost}index.php/home/Vote_Result/setCandidate`
        const datas = {
          type: 'waiver',
          vote_id: this.detail.vote_id,
          area_id: loadVillageId(),
          user_id: loadUserId()
        }
        this.$http.post(url, qs.stringify(datas), {headers: {'Content-Type': 'application/x-www-form-urlencoded'}}).then(res => {
          // console.log(res)
          if (res.data.code === 200) {
            Indicator.close()
            Toast({
              message: res.data.data.message,
              position: 'middle',
              duration: 1000
            })
            // this.popupVisible = false
            // this.sureVisible = false
            this.giveupVisible = false
            // flag 1:表示跳转 0：表示不跳转
            if (res.data.data.flag === 1) {
              if (res.data.data.data.type === 'vote') {
                this.$router.replace('/home/Vote/' + res.data.data.data.id)
              } else if (res.data.data.data.type === 'voting') {
                this.$router.replace('/home/voting/' + res.data.data.data.id + '/' + res.data.data.data.can_type)
                this.$router.go(0) // 刷新
                this._getVotingList()
              } else if (res.data.data.data.type === 'TakeIn') {
                this.$router.replace('/home/TakeIn/' + res.data.data.data.id)
              } else if (res.data.data.data.type === 'TakeScore') {
                this.$router.replace('/home/SatisForm/' + res.data.data.data.id)
              }
            } else if (res.data.data.flag === 0) {
              // this.$router.go(-6)
              this.$router.replace('/home')
            }
          }
          if (res.data.code === 400) {
            Indicator.close()
            Toast({
              message: '对不起，该项投票已由同套房屋的其他业主完成',
              position: 'middle',
              duration: 2000
            })
            this.$router.go(0)
          }
        })
      }
    }
  }
</script>
